package com.qfedu.vhr.framework.config;

import com.qfedu.vhr.framework.entity.Role;
import com.qfedu.vhr.framework.entity.vo.MenuWithRole;
import com.qfedu.vhr.framework.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @author baize
 * @date 2023/1/9
 * @site www.qfedu.com
 */
@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    IMenuService menuService;
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 这个方法的主要作用，是根据当前请求的接口，分析出来当前接口所需要的权限/角色
     *
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation filterInvocation = (FilterInvocation) object;
        //获取当前的请求地址 http://localhost:8081/employee/basic/hello ，这里获取到的就是 /employee/basic/hello
        String requestUrl = filterInvocation.getRequestUrl();
        List<MenuWithRole> menus = menuService.getMenusWithRole();
        for (MenuWithRole menu : menus) {
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                //说明匹配上了，那么当前请求所需要的角色就是
                List<Role> roles = menu.getRoles();
                String[] arrRoles = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    arrRoles[i] = roles.get(i).getName();
                }
                return SecurityConfig.createList(arrRoles);
            }
        }
        //对于没有和数据库中地址匹配上的路径，返回 ROLE_LOGIN，表示当前请求，登录完成之后就可以访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
